<!--
  * 热力图
  * 
-->
<template>
  <default-home-card icon="StarTwoTone" :leftTabs="leftTabs" :tabs="tabs" @tabChange="onTabChange" @leftTabChange="handleLeftTabChange">
    <div style="height: 270px">
      <div id="custom-amap"></div>
    </div>
  </default-home-card>
</template>
<script setup lang="ts">
import _ from 'lodash'
import DefaultHomeCard from '@/views/system/home/components/default-home-card.vue'
import { ref, onMounted } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import { useUserStore } from '@/store/modules/user-store'
import { homeApi } from '@/api/system/home-api'

// 获取地图中心点
const { getCenterLocal } = useUserStore()
const center = getCenterLocal

const SalesDataList = ref()
const map = ref(null)

const leftTabs_type = ref(1)
const leftTabs = ref([
  { key: '1', title: '订单动销热力图' },
  { key: '2', title: '商品动销热力图' }
])

const time_type = ref(1)
const tabs = ref([
  { key: '1', title: '今天' },
  { key: '2', title: '本周' },
  { key: '3', title: '本月' }
])

function onTabChange(key) {
  time_type.value = key
  SalesData()
}

function handleLeftTabChange(key) {
  leftTabs_type.value = key
  SalesData()
}

onMounted(() => {
  SalesData()
})

async function SalesData() {
  const res = await homeApi.getStoreSalesData({ time_type: time_type.value })
  SalesDataList.value = res.data.map((item) => ({
    name: item.store_name,
    lng: parseFloat(item.lon),
    lat: parseFloat(item.lat),
    count: leftTabs_type.value == 1 ? Number(item.order_count) : Number(item.goods_count)
  }))
  initMap()
}

//   初始化地图页面
const initMap = () => {
  window._AMapSecurityConfig = {
    securityJsCode: '98ed597fdab99b3580ded9e3d1f19d4e'
  }
  AMapLoader.load({
    key: 'e3ad28f39ebf5c7d5fb1d7153fb2f3b4',
    version: '2.0',
    plugins: ['AMap.Scale', 'AMap.ToolBar', 'AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.Geocoder', 'AMap.HeatMap', , 'AMap.Marker']
  })
    .then((AMap) => {
      map.value = new AMap.Map('custom-amap', {
        viewMode: '2D',
        zoom: 12,
        showLabel: true,
        resizeEnable: true,
        center: center
      })
      // 初始化热力图
      var heatmap = new AMap.HeatMap(map.value, {
        radius: 40, //给定半径
        opacity: [0, 0.8]
      })
      heatmap.setDataSet({ data: SalesDataList.value })
      map.value.add(heatmap)

      // 创建信息窗口
      const infoWindow = new AMap.InfoWindow({
        content: '', // 初始内容为空
        offset: new AMap.Pixel(0, -30) // 调整信息窗口的偏移量
      })

      // 鼠标移入热力图时显示信息窗口
      map.value.on('mouseover', (e) => {
        const point = new AMap.LngLat(e.lnglat.lng, e.lnglat.lat)
        const closestData = SalesDataList.value.reduce((closest, data) => {
          const distance = AMap.GeometryUtil.distance(point, new AMap.LngLat(data.lng, data.lat))
          return closest ? (distance < AMap.GeometryUtil.distance(point, new AMap.LngLat(closest.lng, closest.lat)) ? data : closest) : data
        }, null)

        if (closestData) {
          const content = `<div style="font-size: 12px; color: ${getColor(closestData.count)}; padding: 5px; border-radius: 5px;">${closestData.name}: ${closestData.count}单</div>`
          infoWindow.setContent(content)
          infoWindow.setPosition(new AMap.LngLat(closestData.lng, closestData.lat))
          infoWindow.open(map.value)
        }
      })

      // 鼠标移出热力图时隐藏信息窗口
      map.value.on('mouseout', () => {
        infoWindow.close()
      })
    })
    .catch((e) => {
      console.log(e)
    })
}

// 根据数据值返回颜色
function getColor(count) {
  if (count < 50) {
    return 'blue' // 低值为蓝色
  } else if (count < 100) {
    return 'green' // 中值为绿色
  } else {
    return 'red' // 高值为红色
  }
}
</script>
<style lang="less" scoped>
#custom-amap {
  width: 100%;
  height: 260px;
  margin-top: 10px;
  border: 1px solid #ccc;
}
</style>
